import SafeCall from "./SafeCall.js";

/**
 * 将 store 中的 captcha 传入即可使用
 */
export default class CaptchaManager {
    /**
     *  CaptchaManager 的单例
     * @type {CaptchaManager}
     */
    static instance = null

    /**
     * @returns {CaptchaManager}
     */
    static getInstance() {
        if (CaptchaManager.instance == null) {
            CaptchaManager.instance = new CaptchaManager();
        }
        return CaptchaManager.instance
    }

    captcha = {
        text: '获取验证码',
        countDown: null
    }
    onStart = []
    onEnd = null
    interval = -1

    start(key) {
        if (this?.interval !== -1) return

        new Promise((resolve, reject) => SafeCall(this.onStart[key], {resolve, reject}))
            .then(() => {
                if (this?.captcha?.countDown == null) this.captcha.countDown = 60
                this.update()
            }).catch(() => this.clear())
    }

    update() {
        if (this.captcha?.countDown >= 0 && this.captcha?.countDown <= 60) {
            this.interval = setInterval(() => {
                this.captcha.countDown -= 1

                if (this.captcha?.countDown <= 0) {
                    this.clear()
                }
            }, 1000)
        }
    }

    clear() {
        SafeCall(this.onEnd)
        this.captcha.countDown = null
        clearInterval(this.interval)
        this.interval = -1
    }
}